#include "TexturesManager.h"

TexturesManager::TexturesManager(void)
{
}

TexturesManager::~TexturesManager(void)
{
	std::map<std::string, Texture*>::iterator i;
	for (i = textures.begin(); i != textures.end(); i++)
		delete (*i).second;
	
	textures.clear();
}

void TexturesManager::Load(const char *path, const char *ext)
{
	std::string searchPath = path;
	searchPath += "\\*.";
	searchPath += ext;

	WIN32_FIND_DATA fd;

	HANDLE hfile = FindFirstFile(searchPath.c_str(), &fd);
	if (hfile != INVALID_HANDLE_VALUE)
	{
		BOOL doSearch = true;
		while (doSearch)
		{
			std::string texPath = path;
			texPath += "\\";
			texPath += fd.cFileName;
			Texture *tex = TextureLoader::LoadFromFile(texPath.c_str());

			std::string texFileName = fd.cFileName;
			Add(texFileName.substr(0, texFileName.size() - 4).c_str(), tex);

			doSearch = FindNextFile(hfile, &fd);
		}

		FindClose(hfile);
	}
}

void TexturesManager::Add(const char *name, Texture *res)
{
	textures[name] = res;
}

Texture * TexturesManager::Get(const char *name)
{
	std::map<std::string, Texture*>::iterator i = textures.find(name);
	if (i == textures.end())
		return NULL;

	return (*i).second;
}

int TexturesManager::GetCount()
{
	return (int)textures.size();
}

void TexturesManager::Get(int i, char *name, Texture *&res)
{
	std::map<std::string, Texture*>::iterator it = textures.begin();
	while (i--)
		it ++;

	strcpy(name, (*it).first.c_str());
	res = (*it).second;
}
